<template>
  <div class="file-manage">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <span>文件上传</span>
        </div>
      </template>
      <el-upload
        class="upload-demo"
        :action="`${baseUrl}/api/file/upload`"
        :headers="headers"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        multiple>
        <el-button type="primary">点击上传</el-button>
        <template #tip>
          <div class="el-upload__tip">支持任意类型文件上传</div>
        </template>
      </el-upload>
    </el-card>

    <el-card class="file-list-card">
      <template #header>
        <div class="card-header">
          <span>文件列表</span>
          <el-button type="primary" @click="refreshList">刷新</el-button>
        </div>
      </template>
      <el-table :data="fileList" style="width: 100%">
        <el-table-column prop="fileName" label="文件名" />
        <el-table-column prop="fileType" label="类型" width="100" />
        <el-table-column prop="fileSize" label="大小" width="120">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="downloadCount" label="已下载次数" width="120">
          <template #default="scope">
            {{ scope.row.downloadCount }}
          </template>
        </el-table-column>
        <el-table-column prop="residualDegree" label="剩余下载次数" width="180">
          <template #default="scope">
            <div class="download-count-cell">
              <span>{{ scope.row.residualDegree }}</span>
              <el-button 
                type="primary" 
                link
                @click="handleUpdateDownloadCount(scope.row)">
                修改
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="handleDownload(scope.row)">下载</el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleToggleStatus(scope.row)">
              {{ scope.row.status === 0 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加修改下载次数的对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改剩余下载次数"
      width="30%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="剩余下载次数">
          <el-input-number 
            v-model="form.residualDegree" 
            :min="0"
            controls-position="right" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpdateDownloadCount">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import { API_BASE_URL } from '@/config'

const baseUrl = API_BASE_URL
const headers = {
  Authorization: getToken()
}

const fileList = ref([])

// 添加新的响应式变量
const dialogVisible = ref(false)
const form = ref({
  id: null,
  residualDegree: 0
})

// 获取文件列表
const getFileList = async () => {
  try {
    const res = await fetch(`${baseUrl}/api/file/list`, {
      headers: {
        Authorization: getToken()
      }
    })
    const data = await res.json()
    if (data.code === 0) {
      fileList.value = data.data
    }
  } catch (error) {
    ElMessage.error('获取文件列表失败')
  }
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  if (response.code === 0) {
    ElMessage.success('上传成功')
    getFileList()
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 上传失败回调
const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 上传前的检查
const beforeUpload = (file) => {
  return true
}

// 下载文件
const handleDownload = (row) => {
  window.open(`${baseUrl}/admin/file/download/${row.id}`)
}

// 切换文件状态
const handleToggleStatus = async (row) => {
  try {
    const res = await fetch(`${baseUrl}/api/file/status`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: getToken()
      },
      body: `id=${row.id}&status=${row.status === 0 ? 1 : 0}`
    })
    const data = await res.json()
    if (data.code === 0) {
      ElMessage.success('状态更新成功')
      getFileList()
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 删除文件
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await fetch(`${baseUrl}/api/file/delete/${row.id}`, {
        method: 'POST',
        headers: {
          Authorization: getToken()
        }
      })
      const data = await res.json()
      if (data.code === 0) {
        ElMessage.success('删除成功')
        getFileList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

// 刷新列表
const refreshList = () => {
  getFileList()
}

// 打开修改下载次数对话框
const handleUpdateDownloadCount = (row) => {
  form.value.id = row.id
  form.value.residualDegree = row.residualDegree
  dialogVisible.value = true
}

// 提交修改下载次数
const submitUpdateDownloadCount = async () => {
  try {
    const params = new URLSearchParams()
    params.append('id', form.value.id)
    params.append('residualDegree', form.value.residualDegree)

    const res = await fetch(`${baseUrl}/api/file/update/degree`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: getToken()
      },
      body: params
    })
    const data = await res.json()
    
    if (data.code === 0) {
      ElMessage.success('修改成功')
      dialogVisible.value = false
      getFileList() // 刷新列表
    } else {
      ElMessage.error(data.message || '修改失败')
    }
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

onMounted(() => {
  getFileList()
})
</script>

<style scoped>
.file-manage {
  padding: 20px;
}
.upload-card,
.file-list-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.upload-demo {
  width: 100%;
}

.download-count-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 